//
//  TCPManage.m
//  AIM
//
//  Created by user10 on 2017/8/30.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "TCPManage.h"
#import <GCDAsyncSocket.h>
#import "logModel.h"
#import "DataBase.h"
#define tcpPort 9997
@interface TCPManage ()<GCDAsyncSocketDelegate>
@property (nonatomic,strong)NSString *dataType;

@property (nonatomic,strong)NSString *textDataString;
@property (nonatomic,strong)NSString *fileName;
@property (nonatomic,strong)NSData *data;

@end

GCDAsyncSocket *tcpSocket;

@implementation TCPManage

static TCPManage *myTCPManage = nil;

+ (instancetype)shareTCPManage{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        myTCPManage = [[TCPManage alloc]init];
        [myTCPManage createClientTcpSocket];
    });
    return myTCPManage;
}

- (void)createClientTcpSocket{
    tcpSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)connect:(NSString *)type{
    _dataType = type;
    [tcpSocket connectToHost:[NSUD objectForKey:@"URL"] onPort:tcpPort viaInterface:nil withTimeout:-1 error:nil];
}
- (void)getName:(NSString *)name{
    _fileName = name;
}

- (void)writeData:(NSData *)data{
    [tcpSocket writeData:data withTimeout:-1 tag:10];
}

- (void)reciveText:(NSString *)str{
    _textDataString = str;
}
- (void)reciveData:(NSData *)data{
    _data = data;
}

#pragma mark - GCDAsyncSocket delegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    //    NSLog(@"连接成功  服务器ip: %@",host);
    [tcpSocket readDataWithTimeout:- 1 tag:50];
}

// 收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    //    [self sendMessage:text andType:@1];
    [tcpSocket readDataWithTimeout:- 1 tag:50];
    if ([text isEqualToString:@"OK"]) {
        NSDate *date = [NSDate date]; // 获得时间对象
        
        NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
        
        [forMatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
        
        NSString *dateStr = [forMatter stringFromDate:date];
        
        logModel *log = [[logModel alloc]init];
        
        if ([_dataType isEqualToString:@"string"]) {
            log.time = dateStr;
            log.opration = @"Comment success";
            log.type = _dataType;
            log.filename = _fileName;
            [[DataBase sharedDataBase]addLogModel:log];
            NSString *strResult = _textDataString;
            NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
            [tcpSocket writeData:data withTimeout:- 1 tag:10];
            
            double delayInSeconds = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                if ([self.delegate respondsToSelector:@selector(refresh)]) {
                    // 调用代理对象的刷新方法，代理对象去实现方法
                    [self.delegate refresh];
                }
                [tcpSocket disconnect];
            });
        }else if ([_dataType isEqualToString:@"photo"]){
            log.time = dateStr;
            log.opration = @"Comment success";
            log.type = _dataType;
            log.filename = _fileName;
            [[DataBase sharedDataBase]addLogModel:log];
            [tcpSocket writeData:_data withTimeout:- 1 tag:20];
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                if ([self.delegate respondsToSelector:@selector(refresh)]) {
                    // 调用代理对象的刷新方法，代理对象去实现方法
                    [self.delegate refresh];
                }
                [tcpSocket disconnect];
                
            });
        }else if ([_dataType isEqualToString:@"movie"]){
            log.time = dateStr;
            log.opration = @"Comment success";
            log.type = _dataType;
            log.filename = _fileName;
            [[DataBase sharedDataBase]addLogModel:log];
            [tcpSocket writeData:_data withTimeout:- 1 tag:30];
            double delayInSeconds = 3.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                if ([self.delegate respondsToSelector:@selector(refresh)]) {
                    // 调用代理对象的刷新方法，代理对象去实现方法
                    [self.delegate refresh];
                }
                [tcpSocket disconnect];
            });
        }else{
            log.time = dateStr;
            log.opration = @"Comment success";
            log.type = _dataType;
            log.filename = _fileName;
            [[DataBase sharedDataBase]addLogModel:log];
            [tcpSocket writeData:_data withTimeout:- 1 tag:40];
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                if ([self.delegate respondsToSelector:@selector(refresh)]) {
                    // 调用代理对象的刷新方法，代理对象去实现方法
                    [self.delegate refresh];
                }
                [tcpSocket disconnect];
            });
        }
    }
}

@end
